import { defineStore } from 'pinia'

export const useDeviceStore = defineStore('device', {
  state: () => ({
    devices: [
      // 天线类设备示例
      {
        id: 'GRAS-3-001',
        name: 'GRAS3天线',
        type: 'antenna',
        category: '天线类',
        status: 'online',
        lastUpdate: '2024-02-10 13:14:25',
        data: {
          '馈源编号': 'FY-001',
          '方位角': '120.5°',
          '俯仰角': '45.2°',
          '方位驱动电源': 'normal',
          '俯仰驱动电源': 'normal',
          '方位驱动器': 'normal',
          '俯仰驱动器': 'normal',
          '方位软件限位': 'normal',
          '俯仰软件限位': 'normal',
          '方位硬件限位': 'normal',
          '俯仰硬件限位': 'normal',
          '俯仰锁定状态': 'unlocked'
        },
        parameterTypes: {
          '馈源编号': 'info',
          '方位角': 'critical',
          '俯仰角': 'critical',
          '方位驱动电源': 'critical',
          '俯仰驱动电源': 'critical',
          '方位驱动器': 'critical',
          '俯仰驱动器': 'critical',
          '方位软件限位': 'normal',
          '俯仰软件限位': 'normal',
          '方位硬件限位': 'normal',
          '俯仰硬件限位': 'normal',
          '俯仰锁定状态': 'critical'
        },
        alarms: []
      },
      // 高频接收机示例
      {
        id: 'GRAS-R-001',
        name: 'GRAS高频接收机',
        type: 'receiver',
        category: '高频接收机类',
        status: 'warning',
        lastUpdate: '2024-02-10 13:14:20',
        data: {
          '放大器电压': '12.5V',
          '放大器电流': '2.1A',
          '真空度': '1.2e-6',
          '杜瓦瓶温度': '-196.5℃'
        },
        parameterTypes: {
          '放大器电压': 'critical',
          '放大器电流': 'critical',
          '真空度': 'normal',
          '杜瓦瓶温度': 'normal'
        },
        alarms: []
      },
      // 光端机示例
      {
        id: 'GRAS-O-001',
        name: 'GRAS光端机',
        type: 'optical',
        category: '传输光端机类',
        status: 'error',
        lastUpdate: '2024-02-10 13:14:15',
        data: {
          '开关状态': 'on',
          '光功率': '-15dBm'
        },
        parameterTypes: {
          '开关状态': 'critical',
          '光功率': 'critical'
        },
        alarms: []
      },
      // 时码器示例
      {
        id: 'CE-7-001',
        name: '密云时码器',
        type: 'timecode',
        category: '保障设备类',
        status: 'online',
        lastUpdate: '2024-02-10 13:14:10',
        data: {
          '开关状态': 'on',
          'GPS锁定状态': 'locked',
          '北斗锁定状态': 'locked',
          '时钟锁定状态': 'locked'
        },
        parameterTypes: {
          '开关状态': 'critical',
          'GPS锁定状态': 'critical',
          '北斗锁定状态': 'normal',
          '时钟锁定状态': 'critical'
        },
        alarms: []
      }
    ],
    currentDevice: null,
    alarmHistory: [],
    // 设备参数阈值设置
    parameterSettings: {
      antenna: {
        '方位角': { min: 0, max: 360 },
        '俯仰角': { min: 0, max: 90 }
      },
      receiver: {
        '放大器电压': { min: 11.5, max: 13.5 },
        '放大器电流': { min: 1.8, max: 2.5 },
        '真空度': { max: 5e-6 },
        '杜瓦瓶温度': { max: -190 }
      },
      optical: {
        '光功率': { min: -20, max: -10 }
      }
    }
  }),

  getters: {
    getDeviceById: (state) => (id) => {
      return state.devices.find(device => device.id === id)
    },
    
    activeAlarms: (state) => {
      return state.devices.reduce((alarms, device) => {
        if (device.alarms.length > 0) {
          alarms.push({
            deviceId: device.id,
            deviceName: device.name,
            alarms: device.alarms
          })
        }
        return alarms
      }, [])
    },

    hasActiveAlarms: (state) => {
      return state.devices.some(device => device.alarms.length > 0)
    },

    getDeviceStatus: (state) => (id) => {
      const device = state.devices.find(d => d.id === id)
      return device ? device.status : 'unknown'
    },

    getParameterStatus: (state) => (device, paramName) => {
      if (!device || !device.data[paramName]) return 'normal'
      
      const paramType = device.parameterTypes[paramName]
      const value = device.data[paramName]
      const settings = state.parameterSettings[device.type]
      
      // 如果设备离线，所有参数显示为灰色
      if (device.status === 'offline') return 'offline'
      
      // 对于开关状态的判断
      if (typeof value === 'string' && ['on', 'off', 'locked', 'unlocked', 'normal'].includes(value.toLowerCase())) {
        if (value.toLowerCase() === 'off') return paramType === 'critical' ? 'error' : 'warning'
        if (value.toLowerCase() === 'unlocked' && paramName.includes('锁定')) return 'error'
        return 'normal'
      }
      
      // 对于数值类型的判断
      if (settings && settings[paramName]) {
        const numValue = parseFloat(value)
        const { min, max } = settings[paramName]
        
        if (min !== undefined && numValue < min) return paramType === 'critical' ? 'error' : 'warning'
        if (max !== undefined && numValue > max) return paramType === 'critical' ? 'error' : 'warning'
      }
      
      return 'normal'
    }
  },

  actions: {
    async fetchDevices() {
      try {
        // 模拟API请求
        // const response = await uni.request({
        //   url: '/api/devices',
        //   method: 'GET'
        // })
        // this.devices = response.data
      } catch (error) {
        console.error('获取设备列表失败:', error)
        uni.showToast({
          title: '获取设备列表失败',
          icon: 'none'
        })
      }
    },

    checkDeviceStatus(device) {
      if (!device) return 'unknown'
      
      // 检查所有关键参数的状态
      const criticalParams = Object.keys(device.parameterTypes)
        .filter(key => device.parameterTypes[key] === 'critical')
      
      const hasError = criticalParams.some(param => 
        this.getParameterStatus(device, param) === 'error'
      )
      if (hasError) return 'error'
      
      const hasWarning = Object.keys(device.data).some(param => 
        this.getParameterStatus(device, param) === 'warning'
      )
      if (hasWarning) return 'warning'
      
      return 'online'
    },

    async updateDeviceStatus(deviceId, status) {
      try {
        const device = this.devices.find(d => d.id === deviceId)
        if (device) {
          device.status = status
          device.lastUpdate = new Date().toLocaleString()
          
          // 更新设备状态时检查所有参数
          const newStatus = this.checkDeviceStatus(device)
          if (newStatus !== device.status) {
            device.status = newStatus
            this.addStatusAlarm(device, newStatus)
          }
        }
      } catch (error) {
        console.error('更新设备状态失败:', error)
        uni.showToast({
          title: '更新设备状态失败',
          icon: 'none'
        })
      }
    },

    async updateDeviceData(deviceId, data) {
      try {
        const device = this.devices.find(d => d.id === deviceId)
        if (device) {
          const oldData = { ...device.data }
          device.data = { ...device.data, ...data }
          device.lastUpdate = new Date().toLocaleString()
          
          // 检查参数变化并添加报警
          Object.keys(data).forEach(param => {
            const oldStatus = this.getParameterStatus({ ...device, data: oldData }, param)
            const newStatus = this.getParameterStatus(device, param)
            
            if (newStatus !== oldStatus && newStatus !== 'normal') {
              this.addParameterAlarm(device, param, data[param], newStatus)
            }
          })
          
          // 更新设备整体状态
          device.status = this.checkDeviceStatus(device)
        }
      } catch (error) {
        console.error('更新设备数据失败:', error)
        uni.showToast({
          title: '更新设备数据失败',
          icon: 'none'
        })
      }
    },

    addStatusAlarm(device, status) {
      const statusMap = {
        error: '设备出现严重故障',
        warning: '设备出现异常',
        offline: '设备离线'
      }
      
      if (statusMap[status]) {
        this.addAlarm(device, {
          type: status,
          message: statusMap[status],
          time: new Date().toLocaleString()
        })
      }
    },

    addParameterAlarm(device, param, value, status) {
      const message = `${param}: ${value} ${status === 'error' ? '严重超限' : '超出正常范围'}`
      this.addAlarm(device, {
        type: status,
        message,
        time: new Date().toLocaleString()
      })
    },

    addAlarm(device, alarm) {
      device.alarms.unshift(alarm)
      this.alarmHistory.unshift({
        ...alarm,
        deviceId: device.id,
        deviceName: device.name
      })

      // 保持报警历史记录在合理范围内
      if (this.alarmHistory.length > 100) {
        this.alarmHistory.pop()
      }

      // 如果是错误级别的报警，显示通知
      if (alarm.type === 'error') {
        uni.showToast({
          title: `${device.name}: ${alarm.message}`,
          icon: 'none',
          duration: 3000
        })
      }
    },

    clearAlarms(deviceId) {
      const device = this.devices.find(d => d.id === deviceId)
      if (device) {
        device.alarms = []
        // 重新检查设备状态
        device.status = this.checkDeviceStatus(device)
      }
    },

    setCurrentDevice(device) {
      this.currentDevice = device
    }
  }
}) 